package org.ef.anticheck;

import android.app.Activity;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CallLog;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class QueryFromCallHistory extends Activity implements OnClickListener {

	private Query compositeQuery;

	private static final String TABLE_NAME = "siberian_blacklist";

	// TODO change url
	private static final String URL_PATTERN = "http://173.224.215.10/query?t=1&n={phone}";

	private static final int PICK_PHONE_NUMBER = 1985;

	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		this.setContentView(R.layout.query_from_call_history);

		final Query localQuery = new LocalQuery(
				new DBMgmt(this).getReadableDatabase(), TABLE_NAME);
		final Query remoteQuery = new RemoteQuery(URL_PATTERN);

		this.compositeQuery = new CompositeQuery(localQuery, remoteQuery);

		this.findViewById(R.id.pick_phone_number).setOnClickListener(this);
	}

	public void onClick(final View v) {
		this.startActivityForResult(new Intent(Intent.ACTION_PICK), PICK_PHONE_NUMBER);
	}

	@Override
	protected void onActivityResult(final int requestCode,
			final int resultCode, final Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		switch (requestCode) {
		case PICK_PHONE_NUMBER:
			if (resultCode == RESULT_OK) {
				final long id = ContentUris.parseId(data.getData());

				final Cursor cursor = this.getContentResolver().query(
						data.getData(),
						new String[] { CallLog.Calls.NUMBER }, "_id=?",
						new String[] { Long.toString(id) },
						null);

				cursor.moveToFirst();

				final String phone = cursor.getString(
						cursor.getColumnIndexOrThrow(CallLog.Calls.NUMBER));

				cursor.close();

				((TextView) this.findViewById(R.id.phone)).setText(phone);

				Recoder r = null;
				try {
					r = this.compositeQuery.execute(phone);
				} catch (final QueryException e) {
					r = null;
				}

				if (r == null) {
					((TextView) this.findViewById(R.id.query_result))
					.setText(R.string.empty_query_result);
				} else {
					((TextView) this.findViewById(R.id.query_result))
					.setText(r.toString());
				}
			} else {
				Log.i("E", data.toString());
			}
		default:
			break;
		}
	}

}